from conan import ConanFile
from conan.errors import ConanInvalidConfiguration
from conan.tools.apple import is_apple_os
from conan.tools.cmake import CMake, CMakeToolchain, CMakeDeps, cmake_layout
from conan.tools.files import apply_conandata_patches, copy, export_conandata_patches, get, save, replace_in_file, rmdir, copy
from conan.tools.gnu import PkgConfigDeps
from conan.tools.env import VirtualBuildEnv
from conan.tools.files import apply_conandata_patches, replace_in_file, get, rmdir, copy
from conan.tools.microsoft import is_msvc
from conan.tools.scm import Version
import os


required_conan_version = ">=1.53.0"


class Nghttp3Conan(ConanFile):
    name = "ngtcp2"
    description = "TCP/2 C Library and tools"
    topics = ("tcp", "tcp/2")
    url = "https://github.com/conan-io/conan-center-index"
    homepage = "https://nghttp2.org/ngtcp2/"
    license = "MIT"
    package_type = "library"
    settings = "os", "arch", "compiler", "build_type"
    options = {
        "shared": [True, False],
        "fPIC": [True, False],
        "gnutls": [True, False],
        "openssl": [True, False],
        "wolfssl": [True, False],
        "jemalloc":  [True, False],
    }
    default_options = {
        # please select only one decryption library at the same time
        "shared": False,
        "fPIC": True,
        "gnutls": False,
        "openssl": True,
        "wolfssl": False,
        "jemalloc": False,
    }
    
    def export_sources(self):
        export_conandata_patches(self)

    def config_options(self):
        if self.settings.os == "Windows":
            del self.options.fPIC

    def configure(self):
        if self.options.shared:
            self.options.rm_safe("fPIC")
    
    def requirements(self):
        if self.options.gnutls:
            self.requires("gnutls/[>=3.7.2]")
        if self.options.openssl:
            self.requires("openssl/[>=1.1 <4]")
        if self.options.wolfssl:
            self.requires("wolfssl/5.6.3")
        if self.options.jemalloc:
            self.requires("jemalloc/5.3.0")
        
        self.requires("libev/[>=4.11]")
        self.requires("nghttp3/[>=0.0.0 <1.0.0]")
        self.requires("cunit/2.1-3")
        
    def layout(self):
        cmake_layout(self, src_folder="src")

    def source(self):
        get(self, **self.conan_data["sources"][self.version], strip_root=True)

    def generate(self):
        tc = CMakeToolchain(self)
        tc.variables["ENABLE_SHARED_LIB"] = self.options.shared
        tc.variables["ENABLE_STATIC_LIB"] = not self.options.shared
        tc.variables["ENABLE_LIB_ONLY"] = True
        
        tc.variables["ENABLE_GNUTLS"] = self.options.gnutls
        tc.variables["ENABLE_OPENSSL"] = self.options.openssl
        tc.variables["ENABLE_WOLFSSL"] = self.options.wolfssl
        tc.variables["ENABLE_JEMALLOC"] = self.options.jemalloc
        if is_apple_os(self):
            # workaround for: install TARGETS given no BUNDLE DESTINATION for MACOSX_BUNDLE executable
            tc.cache_variables["CMAKE_MACOSX_BUNDLE"] = False
        tc.generate()
        tc = VirtualBuildEnv(self)
        tc.generate(scope="build")        
        tc = CMakeDeps(self)
        tc.generate()

    def _patch_sources(self):
        apply_conandata_patches(self)
        
        replace_in_file(self, os.path.join(self.source_folder, "CMakeLists.txt"),
                              "cmake_minimum_required(VERSION 3.20)",
                              "cmake_minimum_required(VERSION 3.16)\ninclude(TestBigEndian)")
        replace_in_file(self, os.path.join(self.source_folder, "CMakeLists.txt"),
                              "if(${CMAKE_C_BYTE_ORDER} STREQUAL \"BIG_ENDIAN\")",
                              "test_big_endian(HOST_BIG_ENDIAN)\nif(HOST_BIG_ENDIAN)")

        replace_in_file(self, os.path.join(self.source_folder, "CMakeLists.txt"),
                              "add_subdirectory(examples)",
                              "")

    def build(self):
        self._patch_sources()
        cmake = CMake(self)
        cmake.configure()
        cmake.build()

    def package(self):
        copy(self, pattern="COPYING", dst=os.path.join(self.package_folder, "licenses"), src=self.source_folder)
        cmake = CMake(self)
        cmake.install()
        rmdir(self, os.path.join(self.package_folder, "share"))
        rmdir(self, os.path.join(self.package_folder, "lib", "pkgconfig"))

    def package_info(self):
        self.cpp_info.set_property("cmake_find_mode", "both")
        self.cpp_info.set_property("cmake_file_name", "ngtcp2")
        self.cpp_info.set_property("cmake_target_name", "ngtcp2::ngtcp2")
        self.cpp_info.set_property("pkg_config_name", "ngtcp2")
        
        self.cpp_info.libs = ["ngtcp2"]
        if is_msvc(self) and not self.options.shared:
            self.cpp_info.defines.append("NGTCP2_STATICLIB")

        self.cpp_info.names["cmake_find_package"] = "ngtcp2"
        self.cpp_info.names["cmake_find_package_multi"] = "ngtcp2"